import api from '../../../fetch/api'
import { deepCopyObj } from '../../../assets/js/help';

export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (!/^(?!_)(?!.*?_$)[a-zA-Z0-9_]{6,16}$/.test(value)) {
          callback(new Error("请输入6到16位不含特殊字符的密码"));
        }
      }
      callback();
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.traderModalData.basicData.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var validatePassEdit = (rule, value, callback) => {
      if (value === "") {
        callback();
      } else {
        if (!/^(?!_)(?!.*?_$)[a-zA-Z0-9_]{6,16}$/.test(value)) {
          callback(new Error("请输入6到16位不含特殊字符的密码"));
        } else {
          if (this.traderModalData.basicData.confirmPassword !== "") {
            this.$refs.trader_form.validateField("confirmPassword");
          }
          callback();
        }
      }
    };
    var validatePass2Edit = (rule, value, callback) => {
      if (value === "" && this.traderModalData.basicData.password === "") {
        callback();
      } else if (value !== this.traderModalData.basicData.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var telephone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入电话号码"));
      }
      if (!/^1\d{10}$/.test(value)) {
        callback(new Error("请输入正确的电话号码"));
      } else {
        callback();
      }
    };
    var checkMaxBuyNum = (rule, value, callback) => {
      if (value === null || value === "") {
        return callback(new Error("数量不能为空"));
      }
      if (!/^[1-9]+[0-9]*$/.test(value)) {
        return callback(new Error("请输入大于0的数量"));
      }
      callback();
    };
    var checkUserCount = (rule, value, callback) => {
      if (value === null || value === "") {
        return callback(new Error("请输入发放员最大数量"));
      } else if (value === 0 || value === "0") {
        return callback();
      } else if (!/^[0-9]*[1-9][0-9]*$/.test(value)) {
        return callback(new Error("请输入大于等于0的正整数"));
      } else {
        callback();
      }
    };
    var checkDuplicatedName = (rule, value, callback) => {
      //检查是否重复名称
      API.coupon
        .checkDuplicatedName({ name: value, traderId: this.traderModalData.basicData.id })
        .then(
          res => {
            if (res.valid) {
              callback();
            } else {
              callback(new Error("此名称已被占用"));
            }
          },
          err => {}
        );
    };
    var checkDuplicatedTel = (rule, value, callback) => {
      //检查是否重复名称
      API.coupon
        .checkDuplicatedTel({ tel: value, id: this.traderModalData.basicData.id })
        .then(
          res => {
            if (res.valid) {
              callback();
            } else {
              callback(new Error("此号码已被占用"));
            }
          },
          err => {}
        );
    };
    return {
      onlineSaleStatus: '',
      traderstatus: "new", //new:新增商家; basicInfo:编辑; shoppingSetup:购买设置; moreSetting:更多设置; settingPwd:密码设置
      traderModalStatus: 1, //修改弹框状态(1:基础信息;2:更多设置;3:重置商家密码;4:购买配置)
      picShow: '', //更多设置-商家图片展示
      uiOpt:{
        checkAll: false,
        isIndeterminate: false
      },
      traderRules: {
        parkId:[{required: true, message: "请选择停车场", trigger: "change"}],
        password: [
          { required: true, validator: validatePass, trigger: "change" }
        ],
        confirmPassword: [
          { required: true, validator: validatePass2, trigger: "change" }
        ],
        passwordEdit: [{ validator: validatePassEdit, trigger: "change" }],
        confirmPasswordEdit: [
          { validator: validatePass2Edit, trigger: "change" }
        ],
        name: [
          { required: true, message: "请输入商家名称", trigger: 'change' },
          {
            min: 2,
            max: 15,
            message: "长度在 2 到 15 个字符",
            trigger: "change"
          },
          { validator: checkDuplicatedName, trigger: 'change' }
        ],
        tel: [{ required: true, validator: telephone, trigger: 'change' },
              { validator: checkDuplicatedTel, trigger: 'change'}],
        contact: [
          { required: true, message: "此项不能为空", trigger: "change" }
        ],
        maxBuyNum: [{ validator: checkMaxBuyNum, trigger: "change" }],
        address: [
          { min: 2, max: 100, message: "最大100 个字符", trigger: "change" }
        ],
        otherType: [
          { required: true, message: "请输入自定义类型", trigger: "change" },
          {
            min: 2,
            max: 30,
            message: "长度在 2 到 30 个字符",
            trigger: "change"
          }
        ],
        userCount: [{ validator: checkUserCount, trigger: "blur" }]
      },
      traderModalData: {
        tabName: '', //tab切换
        basicData:{ //基础信息obj
          id: null,
          name: "", //商家名称
          parkName: null,
          parkId: null,
          type: '', 
          defaultType: "美食", //商家类型
          otherType: "", //自定义类型
          contact: "", //联系人
          tel: "", //联系人电话
          password: "", //登录密码
          confirmPassword: "", //确认登录密码
        },
        shoppingSetup:{ //购买配置obj
          couponName: '', //优惠券名称
          checkedCoupons: [],
          couponList: [],
          couponIdListStr:'',
        },
        superiorData:{ //更多设置obj
          pic:'',
          picShow: '', //商家图片
          address: "", //商家地址
          traderUrl: "", //商家链接
          isLimitBuy: 0, //限制购买
          maxBuyNum: "", //限制数量
          userCount:2, //发放员数量
          supportFixedQr: "", //固定二维码发券
          grantMethod: "", //发券方式
        }
      },
      parkingLotList: [], //停车场列表
    }
  },
  created() {
    this.toBase(this);
    this.fetchTraderCouponOnlineSaleStatus()
  },
  mounted() {
    const self = this
    window.addEventListener('storage', function(ev) {
			if (ev.key == 'onlineSaleStatus_set') {
        if(ev.newValue===null || ev.newValue==='') return;
				let newVal = JSON.parse(ev.newValue)
				self.onlineSaleStatus = Number(newVal)
			}
		});
  },
  methods: {
    // 售卖操作
    toSell(rowData){
      this.$refs.sellManageComponent.SellCouponsModal_open2(rowData)
    },
    // 获取当前帐号的线上购买的开关状态
    fetchTraderCouponOnlineSaleStatus() {
      let self = this;
      API.fetchGet("/trader/getTraderCouponOnlineSaleStatus.do", {}).then(
        res => {
          if (res.status == 1) {
            self.onlineSaleStatus = res.data;
          }
        },
        err => {}
      );
    },
    // 优惠券列表搜索框
    searchCouponKeyWord(){
      let keyword = this.traderModalData.shoppingSetup.couponName
      this.traderModalData.shoppingSetup.couponList.forEach(element=>{
        if(element.name.indexOf(keyword)>-1 || !keyword){
          element.isHidden = false
        }else{
          element.isHidden = true
        }
      })
      this.traderModalData.shoppingSetup.couponList.push({})
      this.$nextTick(()=>{
        this.traderModalData.shoppingSetup.couponList.pop()
      })
    },
    handleCheckAllChange(val) {
      let allCoupon = []
      this.traderModalData.shoppingSetup.couponList.forEach(element=>{
        if(!element.isHidden){
          allCoupon.push(element.id)
        }
      })
      this.traderModalData.shoppingSetup.checkedCoupons = val ? allCoupon : [];
      this.uiOpt.isIndeterminate = false;
    },
    handleCheckedChange(value) {
      let checkedCount = value.length;
      this.uiOpt.checkAll = checkedCount === this.traderModalData.shoppingSetup.couponList.length;
      this.uiOpt.isIndeterminate = checkedCount > 0 && checkedCount < this.traderModalData.shoppingSetup.couponList.length;
    },
    getList() {
      this.getItemList();
    },
    //图片转bas64
    toBase(vm) {
      $(document).on('change', "#traderpic", function () {
        var file = this.files[0];
        var reader = new FileReader();
        if (!/image\/\w+/.test(file.type)) {
          // icon: 0:普通提示 1：正确的提示 2： 错误提示
          // time: 不填默认1000ms
          vm.showToast('请确保文件为图像类型', 2, 2000)
          return false;
        }
        vm.traderModalData.picName = file.name;
        reader.readAsDataURL(file);
        reader.onload = function (e) {
          var res = e.target.result.replace("data:image/png;base64,", "");
          res = res.replace("data:image/jpg;base64,", "");
          vm.picShow = res;
          res = res.replace("data:image/jpeg;base64,", "");
          vm.traderpic = res;
        };
      })
    },
    // 启用
    enable_confirm(){
      let self = this;
      if (!this.selectionList.length) {
          self.showToast('请选择一条记录');
          return false;
      }
      self.showDialog('是否启用所选商家？',['确认','取消'],function(){
        let idList = [];
        let params = {};
        self.selectionList.forEach(element => {
          idList.push(element.id);
        });
        params.traderIds = idList.join(",");
        api.fetchGet('/trader/enableTraderList.do', params).then(res => {
          self.showToast(res.message, 1, 2000)
          self.getList();
        }, err => {})
      })
    },
    // 禁用
    disable_comfirm(){
      let self = this;
      if (!this.selectionList.length) {
        self.showToast('请选择一条记录');
        return false;
      }
      self.showDialog('是否禁用所选商家？',['确认','取消'],function(){
        let idList = [];
        let params = {};
        self.selectionList.forEach(element => {
          idList.push(element.id);
        });
        params.traderIds = idList.join(",");
        api.fetchGet('/trader/disableTraderList.do', params).then(res => {
          self.showToast(res.message, 1, 2000)
          self.getList();
        }, err => {})
      })
    },
    async traderModal_edit(data,editStatus) { //编辑商家基本信息
      var _this = this;
      var sourceData = data;
      var editdata = {
        tabName: '',
        url: "/trader/editTrader.do",
        basicData:{ //基础信息obj
          id: sourceData.id,
          name: sourceData.name, //商家名称
          parkName: sourceData.parkName,
          parkId: sourceData.parkId,
          type: '', 
          defaultType: sourceData.type, // 商家类型
          otherType: sourceData.type == '其他' ? sourceData.otherType : null, //自定义类型
          contact: sourceData.contact, //联系人
          tel: sourceData.tel, //联系人电话
          password: "", //登录密码
          confirmPassword: "", //确认登录密码
        },
        shoppingSetup:{ //购买配置obj
          couponName: '', //优惠券名称
          checkedCoupons: [],
          couponList: [],
          couponIdListStr:'',
        },
        superiorData:{
          pic:sourceData.pic,
          picShow: '', //商家图片
          address: sourceData.address, //商家地址
          traderUrl: sourceData.traderUrl, //商家链接
          isLimitBuy: sourceData.isLimitBuy == '否' ? 0 : 1, //限制购买
          maxBuyNum: !(sourceData.isLimitBuy == '否') ? sourceData.maxBuyNum : null, //限制数量
          userCount: sourceData.userCount, //发放员数量
          supportFixedQr: sourceData.supportFixedQr == '是' ? 1 : 0, //固定二维码发券
          grantMethod: sourceData.grantMethod == '商家发券' ? 0 : 1, //发券方式
        }
      };
      _this.traderpic = '' 
      _this.picShow = sourceData.pic
      _this.traderModalStatus = editStatus
      _this.uiOpt = {
        checkAll: false,
        isIndeterminate: false
      }
      _this.traderModalData = deepCopyObj(editdata)
      if(editStatus==1){ //编辑基本信息
        _this.traderstatus = "basicInfo";
        _this.traderModalData.tabName = 'basicTab'
        await _this.getParkingLotList() //获取停车场列表
        _this.toOpenModal('traderModal')
      }else if(editStatus==4){ //购买配置
        _this.traderstatus = "shoppingSetup";
        _this.traderModalData.tabName = 'higherTab'
        _this.fetchSelectedCoupons(sourceData.id); //获取某个商家的购买配置
        _this.toOpenModal('traderModal')
      }else if(editStatus==2){ //更多设置
        _this.traderstatus = "moreSetting";
        _this.toOpenModal('traderModal')
      }else{
        _this.traderstatus = 'settingPwd' //设置密码
        _this.toOpenModal('pwdFormModal')
      }
    },
    // 获取某个商家的购买配置
    fetchSelectedCoupons(traderId){
      let self = this
      let params = {
        traderId: traderId,
        sort: true
      }
      API.fetchGet('/trader/getCoupon2Buy.do',params).then(res=>{
        self.traderModalData.shoppingSetup.checkedCoupons = []
        self.traderModalData.shoppingSetup.couponList = res.data
        self.traderModalData.shoppingSetup.couponList.forEach(element=>{
          element.isHidden = false
          if(element.checked){
            self.traderModalData.shoppingSetup.checkedCoupons.push(element.id)
          }
        })
      },err=>{})
    },
    // tab步骤切换
    toggleTab(tabName){
      if(this.traderModalData.tabName==tabName){
        return;
      }
      this.traderModalData.tabName = tabName
    },
    // 购买设置-保存
    traderModal_save_shooppingSetup(modalName){
      let self = this
      let params = {
        traderId: self.traderModalData.basicData.id,
      }
      if(self.traderModalData.shoppingSetup.checkedCoupons && self.traderModalData.shoppingSetup.checkedCoupons.length){
        params.couponIdListStr = self.traderModalData.shoppingSetup.checkedCoupons.join(',')
      }else{
        params.couponIdListStr = ''
      }
      API.fetchPost('/trader/editTraderBuySet.do',params).then(res=>{
        if(res.status==1){
          self.showToast('保存成功',1,2000);
          self.getList()
          self.closed(modalName)
        }
      },err=>{})
    },
    // 获取停车场列表数据
    getParkingLotList(){
      let self = this
      return API.fetchGet('/trader/queryAllPark.do',{}).then(res=>{
        let data = res.data;
        let list = data && data.parkList ? data.parkList : [];
        self.parkingLotList = [];
        list && list.forEach(item => {
          let obj = {
            parkUid: item.pkGlobalid,
            name: item.name, //停车场名
            id: item.id, //停车场id
            area: item.area, //区域
            topArea : ''
          };
          if(item.area){
            // let idx = item.area.indexOf('-')
            // let tmpTopArea = item.area.substring(0,idx)
            let tmpArr = item.area.split('-')
            let tmpTopArea = tmpArr[0]
            obj.topArea = self.adjustProvinceNameOfParkingLot(tmpTopArea)
          }
          self.parkingLotList.push(obj);
        });
        if(self.traderstatus=='new'){ //新增
          self.traderModalData.basicData.parkId = self.parkingLotList[0].parkUid
          self.traderModalData.basicData.parkName = self.parkingLotList[0].name
          self.fetchCouponsOfParking(self.parkingLotList[0].id)
        }
      },err=>{})
    },
    // 调整停车场所属省份名
    adjustProvinceNameOfParkingLot(provinceName){
      if(!provinceName){
        return provinceName
      }
      let idx = 0
      let rsStr = ''
      provinceName = provinceName.replace(/\(.*?\)/g, '')
      if(provinceName.indexOf('省')>-1){
        idx = provinceName.indexOf('省')
      }else if(provinceName.indexOf('自治区')>-1){
        idx = provinceName.indexOf('自治区')
      }else if(provinceName.indexOf('市')>-1){
        idx = provinceName.indexOf('市')  
      }else if(provinceName.length > 6){
        idx = 1
      }
      if(idx!==0){
        rsStr = provinceName.substring(0,idx)
        return rsStr
      }else{
        return provinceName
      }
    },
    // 停车场列表选择停车场
    selectParkingLot(itemId){
      let targetItem = this.parkingLotList.find(item=>{
        return item.parkUid==itemId
      })
      this.traderModalData.basicData.parkName = targetItem.name
      if(this.traderstatus=='new'){
        this.fetchCouponsOfParking(targetItem.id)
      }
    },
    async traderModal_open() {
      var _this = this;
      _this.traderpic = '';
      _this.traderstatus = "new",
      _this.traderModalStatus = 1
      _this.uiOpt = {
        checkAll: false,
        isIndeterminate: false
      }
      _this.traderModalData = {
        tabName: 'basicTab',
        url: "/trader/addTrader.do",
        basicData:{ //基础obj
          id: null,
          name: "", //商家名称
          parkName: null,
          parkId: null,
          type: '', 
          defaultType: "美食", //商家类型
          otherType: "", //自定义类型
          contact: "", //联系人
          tel: "", //联系人电话
          password: "", //登录密码
          confirmPassword: "", //确认登录密码
        },
        shoppingSetup:{ //购买配置obj
          couponName: '', //优惠券名称
          checkedCoupons: [],
          couponList: [],
          couponIdListStr:'',
        },
        superiorData:{ //更多obj
          pic:'',
          picShow: '', //商家图片
          address: "", //商家地址
          traderUrl: "", //商家链接
          isLimitBuy: 0, //不限制购买
          maxBuyNum: '', //限制数量
          userCount:2, //发放员数量
          supportFixedQr: "", //固定二维码发券
          grantMethod: "", //发券方式
        }
      };
      await _this.getParkingLotList()
      _this.toOpenModal('traderModal')
    },
    traderModal_save(modalName) {
      var _this = this;
      _this.$refs['trader_form'].validate((valid) => {
        if (valid) {
          var url = _this.traderModalData.url;
          let params = deepCopyObj(_this.traderModalData.basicData) //基础信息
          let superiorObj = deepCopyObj(_this.traderModalData.superiorData) //更多设置
          Object.assign(params,superiorObj)
          if(_this.traderModalData.shoppingSetup.checkedCoupons && _this.traderModalData.shoppingSetup.checkedCoupons.length){
            params.couponIdListStr = _this.traderModalData.shoppingSetup.checkedCoupons.join(',')
          }
          params.telIsEdit = true;
          if (params.defaultType == "其他") {
            params.type = params.otherType;
          } else {
            params.type = params.defaultType;
          }
          if (_this.traderpic) {
            params.pic = _this.traderpic;
          }else{
            params.pic = ''
          }
          api.fetchPost(url, params).then(response => {
            if (response.status == 1) {
              _this.showToast(response.message, 1, 2000);
              _this.getList();
              _this.resetForm('trader_form');
              _this.closed(modalName);
            } else {
              _this.showToast(res.message, 2, 2000)
              return;
            }
          }, err => {})
        }
      })
    },
    openSelectParkModal() {
      var _self = this;
      _self.initParkTree("ParkTree");
      _self.toOpenModal('selectParkModal');
    },
    initParkTree(treeId) {
      var _self = this;
      API.fetchGet('/parkingBaseData/getParkingBaseDataTree.do', {})
        .then(res => {
          var data = res;
          if (data != null) {
            var nodes = data.data;
            var jsonStr = JSON.stringify(nodes);
            jsonStr = jsonStr.replace(/(\"isArea\"\:true\,)/g, '"isArea": true,"chkDisabled":true, "nocheck":true,');
            var settings = {
              check: {
                enable: true,
                chkStyle: "radio",
                radioType: "all"
              },
              view: {
                showIcon: false,
                showLine: false,
              },
              callback: {
                onClick: function (event, treeId, treeNode) {
                  var treeObj = $.fn.zTree.getZTreeObj('ParkTree');
                  treeObj.checkNode(treeNode, true, false);
                  if (treeNode.isArea) {
                    return;
                  }
                },
              }
            };
            if(_self.traderstatus!='new' && _self.traderModalData.basicData.parkId){  //编辑
              let parkId = _self.traderModalData.basicData.parkId
              jsonStr = jsonStr.replace('"parkId":"'+parkId+'",','"parkId":"'+parkId+'","checked":true,')
              nodes = JSON.parse(jsonStr);
            }else if(_self.traderstatus=='new'){
              if(_self.traderModalData.basicData.parkId){
                let parkId = _self.traderModalData.basicData.parkId
                jsonStr = jsonStr.replace('"parkId":"'+parkId+'",','"parkId":"'+parkId+'","checked":true,')
                nodes = JSON.parse(jsonStr);
              }else{
                nodes = JSON.parse(jsonStr);
                let nodeObj = nodes.children[0] //全国-children
                while(nodeObj.children){
                  nodeObj = nodeObj.children[0]
                }
                nodeObj.checked = true
                _self.traderModalData.basicData.parkName = nodeObj.name;
                _self.traderModalData.basicData.parkId = nodeObj.parkId;
                _self.fetchCouponsOfParking(nodeObj.value)
              }
            }
            $.fn.zTree.destroy("ParkTree");
            let treeObj = $.fn.zTree.init($("#ParkTree"), settings, nodes);
            treeObj.expandAll(true);
          } else {
            _self.showToast('暂时没有停车场可选', 2, 3000);
          }
        }, err => {})
    },
    selectParkSure() {
      var self = this,
        nodes = [];
      var treeObj = $.fn.zTree.getZTreeObj("ParkTree");
      nodes = treeObj.getCheckedNodes(true); // 获取tree被勾选的节点
      if (nodes && nodes.length > 0) {
        var p = nodes[0];
        self.traderModalData.basicData.parkName = p.name;
        self.traderModalData.basicData.parkId = p.parkId;
        if(self.traderstatus=='new'){ //新增
          self.fetchCouponsOfParking(p.value)
        }
        self.closed('selectParkModal');
      } else {
        this.showToast('请选择一个停车场', 0, 2000)
        return;
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 获取停车场对应优惠券数据
    fetchCouponsOfParking(id){
      let self = this
      let params = {
        parkId: id,
        sort: true
      }
      API.fetchGet('/trader/getCoupon2Buy.do',params).then(res=>{
        if(res.data && res.data.length){
          self.traderModalData.shoppingSetup.couponList = res.data
          self.traderModalData.shoppingSetup.couponList.forEach(element=>{
            element.isHidden = false
          })
          self.traderModalData.shoppingSetup.checkedCoupons = []
        }
      },err=>{})
    },
    getItemList() {
      let self = this,
        params = {
          page: this.pageNumber,
          rp: this.pageSize
        };
      self.tbodysInfo = []
      params = $.extend({}, params, self.otherParams, self.searchParams);
      API.coupon.GetTraderListData(params)
        .then(res => {
          let data = res.data,
            list = data.rows;
          self.tbodysInfo = list;
          self.total = data.total;
        }, err => {})
    },
    // 导出
    exportData() {
      let self = this;
      let theadsArr = []
      for(let i = 0; i<self.theadsInfo.length; i++){
        if(self.theadsInfo[i].checked){
          theadsArr.push(self.theadsInfo[i].prop)
        }
      }
      let params = {
        meterList: theadsArr.join(',')
      };
      params = $.extend({}, params, this.otherParams, this.searchParams);
      self.showDialog("是否确认导出?", '', function () {
        self.toExportAsync('trader/exportTrader.do', params)
      })
    },
    // 导入
    importData() {
      var self = this;
      // self.startImportResultTimer(self);
      self.toOpenModal('importModal');
    },
    // 定时器
    startImportResultTimer(self) {
      function intervalFunc() {
        $.ajax({
          url: '/mgr/trader/importTrader.do',
          dataType: "json",
          data: {},
          type: 'get',
          success: function (result) {
            if (result.status == 1) {
              self.importResult = result.data;
              if (!self.importResult || (self.importResult.totalCount == self.importResult.processedCount)) {
                clearInterval(getImportResultTimer);
              }
            }
          }
        }); 
      }
      intervalFunc();
      var getImportResultTimer = setInterval(function () {
        intervalFunc();
      }, 1000);
    },
    getFile(event) {
      this.importFile.importFile = event.target.files[0];
    },
    // 上传文件
    sureImport(event) {
      var self = this;
      event.preventDefault();
      var formData = new FormData();
      formData.append("importFile", self.importFile.importFile);
      formData.append("im12portFile", 'self.importFile.importFile');
      formData.append("filename", self.importFile.importFile.name.replace('.xls', ''));
      if (!self.importFile.importFile) {
        self.showToast('请先选择文件', 1)
        return false;
      }
      var objtype = self.importFile.importFile.name.substring(self.importFile.importFile.name.lastIndexOf(".")).toLowerCase();
      if (objtype != '.xls') {
        self.showToast('只支持xls格式文件', 1)
        return false;
      }
      api.fetchPostFile('/trader/importTrader.do', formData).then(res => {
        if (res.status == 1) {
          self.importResult = res.data;
          self.getList();
        }
      }, err => {});
    },
    // 下载模板
    downloadTmp() {
      var self = this;
      let params = {
        "fileName": "trader_import",
        "fileType": "xls"
      }
      $.ajax({
        url: '/mgr/importFlie/createExcelTmp.do',
        dataType: "json",
        data: params,
        type: 'get',
        success: function (result) {
          var r = result;
          if (r.success) {
            if (r && r.success) {
              self.showToast('下载成功', 1);
              window.location.href = encodeURI("/mgr/common/templateDownload.do?fileName=" + r.fileName);
            } else {
              self.showToast('下载失败', 2);
            }
          }
        }
      }); 
    },
    // 下载错误文件
    downloadError() {
      var self = this;
      if (self.importResult.ossKey != '') {
        API.fetchGet('/authz/user/downloadBatchResult', { ossKey: self.importResult.ossKey }).then(
          res => {
            let data = res.data;
            window.location.href = data;
          },
          err => {}
        );
      } else if(self.importResult.errorFileName != "") {
        window.location.href = encodeURI("/mgr/common/downloadNotDelete.do?fileName=" + self.importResult.errorFileName);
      }
    },
    // 删除记录
    deleteTrader(trader) {
      var self = this;
      var params = {
        id: trader.id,
      };
      self.showDialog("确认删除该商家?", '', function () {
        API.coupon.traderDel(params).then(res => {
          self.showToast('删除成功', 1);
          self.getList();
        }, err => {});
      });
    },
  }
}
